<script setup lang="ts">
import { requiredCheck, singleIpCheck } from "@/utils/verify";
import { reactive, ref } from "vue";
import { addData, editData, getInfo } from "@/api/modules/dynamic-camouflage/network-config";

interface Props {
  title?: string;
  rowData?: Object;
}

import SelectLinksInput from "@/components/SelectLinksInput/index.vue";

const props = withDefaults(defineProps<Props>(), {
  title: "新增网络",
  rowData: undefined
});
defineOptions({
  name: "UpdateForm" // 默认策略
});
import useUpdate from "@/hooks/useUpdate";
import { ifaceAll, ifacemodeUpdate } from "@/api/modules/dynamic-camouflage/line-config";
import { getDataByPage as getFingerData } from "@/api/modules/resource/host-finger";
import { getDataByPage as getHsData } from "@/api/modules/resource/service";

const emits = defineEmits(["success"]);
const { updateFormData, updateFormRef, updateFormRules, submit, showHandle, openHandle, closeHandle } = useUpdate({
  rules: {
    name: [...requiredCheck("请选择链路")],
    password: [...requiredCheck("请输入密码")],
    gateway: [...requiredCheck("请输入网关"), { validator: singleIpCheck }],
    iprange: [...requiredCheck("请输入网段"), { validator: singleIpCheck }],
    iprangeSux: [
      ...requiredCheck(""),
      {
        validator: (rule, value, callback) => {
          if (isNaN(value) || !/^(3[0-2]|[12]?[0-9])$/.test(value)) {
            callback(new Error("格式错误"));
          }
          callback();
        }
      }
    ]
  },
  defaultData: {
    type: "1",
    iprangeSux: "24"
  }
});
const ifaces = ref([]);

async function submitCb() {
  await submit({
    addApi: addData,
    updateApi: editData,
    sendData: {
      name: updateFormData.name,
      destport: "0-65535",
      iprange: updateFormData.iprange + "/" + updateFormData.iprangeSux,
      fingerip: updateFormData.fingers ? updateFormData.fingers.map(item => item.ip).join() : "",
      srvid: updateFormData.hs ? updateFormData.hs.map(item => item.id).join(",") : "",
      type: updateFormData.type,
      id: updateFormData?.id,
      description: updateFormData?.description || "",
      gateway: updateFormData?.gateway
    }
  });
  emits("success");
}

const details = ref();
const pageData = reactive({
  fingerRemoteData: [],
  hsRemoteData: []
});

async function getData() {
  const [res1, res2] = await Promise.all([
    getFingerData({
      curpage: 0,
      perpage: 10000
    }),
    getHsData({
      pageNum: 0,
      pageSize: 10000
    })
  ]);
  pageData.fingerRemoteData = res1.data;
  let data = res2.result.data;
  let arr: any = [];
  data.forEach(item => {
    if (item[0] != 5) {
      let obj = JSON.parse(item[5]);
      let account = "-";
      let password = "-";
      console.log(obj);
      if (obj?.account) {
        account = obj.account[0]?.user;
        password = obj.account[0]?.password;
      }
      if (obj.srvid == 10) {
        password = obj.requirepass;
      }
      arr.push({
        id: item[item.length - 1].replace("/", ""),
        name: item[1],
        proto: item[2],
        port: item[3],
        grade: item[4],
        account,
        password,
        originData: item,
        srvid: obj.srvid,
        isCheck: false
      });
    }
    if (item[0] == 5) {
      let webArr = JSON.parse(item[5]);
      console.log("web==", webArr);
      webArr.app.forEach(val => {
        let priMap = new Map([
          ["1", "低"],
          ["2", "中"],
          ["3", "高"]
        ]);
        arr.push({
          id: val.id,
          name: val.name,
          proto: val.proto,
          port: val.port,
          grade: priMap.get(val.pri.toString()),
          account: "root",
          password: "123456",
          originData: item,
          type: val.type.toString(),
          srvid: webArr.srvid,
          file: val.file,
          isCheck: false
        });
      });
    }
  });
  console.log(res1, res2);
  pageData.hsRemoteData = arr;
  console.log("pageData", pageData);
}

async function openHandleCb() {
  openHandle({
    row: {
      ...props.rowData
    },
    id: props.rowData?.id
  });
  if (props.rowData?.id) {
    await getData();
    const res = await getInfo({
      id: props.rowData?.id
    });
    // const res = {
    //   id: "1",
    //   name: "线路1",
    //   iprange: "12.23.23.1/23",
    //   destport: "0-65535",
    //   fingerip: "0.0.0.1",
    //   srvid: ["SSH伪装服务", "TELNET伪装服务", "FTP伪装服务"],
    //   cfg: null,
    //   state: "1",
    //   uptime: "1756642310"
    // };
    details.value = res;
    updateFormData.destport = res?.destport || "";
    if (res.fingerip) {
      updateFormData.fingers = [pageData.fingerRemoteData.find(item => item.ip === res.fingerip) || ""];
    }
    if (res.srvid) {
      updateFormData.hs = pageData.hsRemoteData.filter(item =>
        res.srvid.find(val => {
          let text = item.name;
          if (text.includes(":")) {
            text = text.split(":")[0];
          }
          return val === text;
        })
      );
    }
  }
}

function changeType(type) {
  if (type == 1) {
    updateFormData.iprangeSux = "24";
  }
  if (type == 2) {
    updateFormData.iprangeSux = "16";
  }
  if (type == 3) {
    updateFormData.iprangeSux = "8";
  }
  if (type == 4) {
    updateFormData.iprangeSux = "";
  }
}
</script>

<template>
  <div class="update-form mg-r-sm update-form-edit" style="display: inline-block;height: 55px" @click="openHandleCb">
    <slot>
      <el-button type="primary">新增</el-button>
    </slot>
  </div>
  <base-dialog @confirm="submitCb()" width="560px" :title="title" v-if="showHandle" v-model="showHandle">
    <div class="details">
      <div class="details-main">
        <el-form ref="updateFormRef" :model="updateFormData" :rules="updateFormRules" label-width="80px" label-suffix="：">
          <el-form-item label="线路" prop="name">
            <SelectLinksInput width="140px" isName placeholder="请选择线路" v-model="updateFormData.name" />
          </el-form-item>
          <el-divider style="width: calc(100% - 40px); margin: 15px auto" />
          <div class="h-box">
            <el-form-item label="类型" prop="type">
              <el-select
                style="width: 140px"
                v-model="updateFormData.type"
                @change="changeType"
                auto-complete="off"
                placeholder="请选择类型"
                maxlength="50"
              >
                <el-option value="1" label="C类"></el-option>
                <el-option value="2" label="B类"></el-option>
                <el-option value="3" label="A类"></el-option>
                <el-option value="4" label="自定义"></el-option>
              </el-select>
            </el-form-item>
            <div class="network-range">
              <el-form-item label="网段" prop="iprange">
                <el-input
                  style="width: 140px"
                  v-model="updateFormData.iprange"
                  auto-complete="off"
                  placeholder="请输入网段"
                  maxlength="50"
                />
              </el-form-item>
              <span class="network-center">/</span>
              <el-form-item prop="iprangeSux">
                <span v-if="updateFormData.type == 1">24</span>
                <span v-else-if="updateFormData.type == 2">16</span>
                <span v-else-if="updateFormData.type == 3">8</span>
                <el-input v-else placeholder="请输入" v-model="updateFormData.iprangeSux" style="width: 80px"></el-input>
              </el-form-item>
            </div>
          </div>
          <div class="h-box">
            <el-form-item label="网关" prop="gateway">
              <el-input
                style="width: 140px"
                v-model="updateFormData.gateway"
                auto-complete="off"
                placeholder="请输入网关"
                maxlength="50"
              />
            </el-form-item>
            <el-form-item label="备注" prop="description">
              <el-input
                type="textarea"
                rows="1"
                style="width: 140px"
                v-model="updateFormData.description"
                auto-complete="off"
                placeholder="请输入备注"
                maxlength="50"
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <template #footer-more-button></template>
  </base-dialog>
</template>

<style lang="scss" scoped>
.network-range {
  display: flex;

  :deep(.el-form-item__content) {
    margin-left: 0px !important;
  }

  .network-center {
    height: 32px;
    align-items: center;
    display: flex;
  }
}
</style>
